package me.zhengjie.ppService;

import lombok.RequiredArgsConstructor;
import me.zhengjie.config.PPNetConfig;
import me.zhengjie.pojo.sqlServer.PPInfo;
import org.springframework.stereotype.Component;

import javax.print.*;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;

@Component
@RequiredArgsConstructor
public class PrintConnection {

    private final PPNetConfig ppNetConfig;

    /**
     * 查找并选择打印机
     */
    public PrintService findPrinter(String printerName) {
        PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
        return Arrays.stream(printServices)
                .filter(ps -> ps.getName().equalsIgnoreCase(printerName))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("Printer not found: " + printerName));
    }

    /**
     * 生成 ZPL 命令，设置二维码和边框
     */
    public String generateZPLWithQRCode(PPInfo info) {
        try {
            // 基础单位换算（1mm≈11.8点）
            final int LABEL_WIDTH = 472;    // 40mm
            final int LABEL_HEIGHT = 1062;  // 90mm
            final int MARGIN = 40;          // 边缘留白

            // 文本区域参数
            final int TEXT_X = 40;
            final int TEXT_Y_START = 50;
            final int LINE_HEIGHT = 40;     // 行间距
            final int FONT_SIZE = 25;       // 字体大小

            // 二维码区域参数
            final int QR_X = 32;
            final int QR_Y = 600;           // 二维码起始位置

            // 构建JSON数据（逐行格式化）
            String jsonData = String.format(
                    "{\n" +
                            "    \"pp\":\"%s\",\n" +
                            "    \"batch\":\"%s\",\n" +
                            "    \"ppBatch\":\"%s\",\n" +
                            "    \"ppMaterial\":\"%s\",\n" +
                            "    \"ppModel\":\"%s\",\n" +
                            "    \"ppMfrs\":\"%s\",\n" +
                            "    \"ppSize\":\"%s\",\n" +
                            "    \"ppQty\":%d,\n" +
                            "    \"ppPd\":\"%s\",\n" +
                            "    \"ppExp\":\"%s\",\n" +
                            "    \"ppWorker\":\"%s\",\n" +
                            "    \"ppDevice\":\"%s\",\n" +
                            "    \"method\":\"%s\"\n" +
                            "}",
                    info.getPp(), info.getBatch(), info.getPpBatch(), info.getPpMaterial(),
                    info.getPpModel(), info.getPpMfrs(), info.getPpSize(), info.getPpQty(),
                    info.getPpPd().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
                    info.getPpExp().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
                    info.getPpWorker(), info.getPpDevice(), info.getMethod()
            );

            // 构建ZPL指令
            StringBuilder zpl = new StringBuilder()
                    .append("^XA\n")
                    // 设置标签参数
                    .append(String.format("^LL%d^PW%d\n", LABEL_HEIGHT, LABEL_WIDTH))
                    // 文本区域
                    .append(buildTextLine("PP", info.getPp(), TEXT_X, TEXT_Y_START, FONT_SIZE))
                    .append(buildTextLine("Batch", info.getBatch(), TEXT_X, TEXT_Y_START + LINE_HEIGHT, FONT_SIZE))
                    .append(buildTextLine("PPBatch", info.getPpBatch(), TEXT_X, TEXT_Y_START + LINE_HEIGHT * 2, FONT_SIZE))
                    .append(buildTextLine("Material", info.getPpMaterial(), TEXT_X, TEXT_Y_START + LINE_HEIGHT * 3, FONT_SIZE))
                    .append(buildTextLine("Model", info.getPpModel(), TEXT_X, TEXT_Y_START + LINE_HEIGHT * 4, FONT_SIZE))
                    .append(buildTextLine("Mfrs", info.getPpMfrs(), TEXT_X, TEXT_Y_START + LINE_HEIGHT * 5, FONT_SIZE))
                    .append(buildTextLine("Size", info.getPpSize(), TEXT_X, TEXT_Y_START + LINE_HEIGHT * 6, FONT_SIZE))
                    .append(buildTextLine("Qty", String.valueOf(info.getPpQty()), TEXT_X, TEXT_Y_START + LINE_HEIGHT * 7, FONT_SIZE))
                    .append(buildTextLine("Prod", info.getPpPd().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")), TEXT_X, TEXT_Y_START + LINE_HEIGHT * 8, FONT_SIZE))
                    .append(buildTextLine("Exp", info.getPpExp().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")), TEXT_X, TEXT_Y_START + LINE_HEIGHT * 9, FONT_SIZE))
                    .append(buildTextLine("Worker", info.getPpWorker(), TEXT_X, TEXT_Y_START + LINE_HEIGHT * 10, FONT_SIZE))
                    .append(buildTextLine("Device", info.getPpDevice(), TEXT_X, TEXT_Y_START + LINE_HEIGHT * 11, FONT_SIZE))
                    .append(buildTextLine("Method", info.getMethod(), TEXT_X, TEXT_Y_START + LINE_HEIGHT * 12, FONT_SIZE))
                    // 二维码区域
                    .append(String.format("^FO%d,%d\n", QR_X, QR_Y))
                    .append("^BQN,2,6\n")  // QR Code版本2，纠错等级Q，尺寸6
                    .append("^FH_^FDMA,").append(jsonData.replace("\"", "\"\"")) // 双引号转义
                    .append("^FS\n")
                    .append("^XZ");

            return zpl.toString();
        } catch (Exception e) {
            return "ERROR: " + e.getMessage();
        }
    }

    public String buildTextLine(String label, String value, int x, int y, int fontSize) {
        return String.format("^FO%d,%d^A0N,%d,%d^FD%s: %s^FS\n",
                x, y, fontSize, fontSize, label, value);
    }

    /**
     * 将ZPL指令发送到打印机
     */
    public void sendTOPrinter(PPInfo ppInfo) throws PrintException {
        // 获取打印服务
        PrintService printService = findPrinter(ppNetConfig.getPrinterName());

        // 创建打印工作
        DocPrintJob printJob = printService.createPrintJob();

        // 创建打印文档
        Doc doc = new SimpleDoc(generateZPLWithQRCode(ppInfo).getBytes(), DocFlavor.BYTE_ARRAY.AUTOSENSE, null);

        // 执行打印
        printJob.print(doc, null);
    }

}
